package test.threads.queue.unstressed;

import com.lmax.disruptor.EventFactory;
import net.jcip.annotations.NotThreadSafe;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import static com.google.common.base.Preconditions.*;

/**
 * @author cheremin
 * @since 29.02.12,  14:10
 */
@NotThreadSafe
public final class EventPool<T> implements EventFactory<T> {
    private final EventFactory<T> factory;
    private final T[] items;

    private int counter = 0;

    @SuppressWarnings( "unchecked" )
    public EventPool( final int size,
                      final EventFactory<T> factory ) {
        this.factory = factory;
        this.items = (T[])new Object[size];
        for ( int i = 0; i < items.length; i++ ) {
            items[i] = factory.newInstance();
        }
    }

    public static <T> EventPool<T> wrap( final EventFactory<T> factory,
                                         final int poolSize ) {
        return new EventPool<T>( poolSize, factory );
    }

    @Override
    public T newInstance() {
        try {
            return items[counter];
        } finally {
            counter = ( counter + 1 ) % items.length;
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append( "EventPool[" )
                .append( factory )
                .append( ':' ).append( items.length )
                .append( ']' );
        return sb.toString();
    }
}
